<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
pc_base::load_sys_class('form', '', 0);
/**
 * 栏目绑定资源
 */
class resources extends admin {
	private $db;
	public $siteid;
	function __construct() {
		$this->db = pc_base::load_model('goods_source_model');
        $this->news = pc_base::load_model('news_nsr_model');
        $this->picture = pc_base::load_model('picture_nsr_model');
        $this->video = pc_base::load_model('video_nsr_model');
        $this->type = pc_base::load_model('source_type_model');
		$this->siteid = get_siteid();
        $model_setting=pc_base::load_model('site_setting_model');
        $this->setting = $model_setting->getValue("sname_link",$this->siteid);
        $this->author_title = $model_setting->getValue("author_title",$this->siteid);
		parent::__construct();
	}

    /**
     * 全部资源列表
     */
    public function init () {
        $show_dialog = $show_validator = true;
        $id = (int) $_GET['id'];
        $goods_model = pc_base::load_model('goods_model');
        $data = $goods_model->get_one(array('id' => $id));
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $where = ' goods_id = ' . $id;
        $list = $this->db->listinfo($where, 'id DESC', $page, 10);
        foreach ($list as $k => $v) {
            if ($v['source_type'] == 1) {
                $info = $this->news->get_one(array('id'=>$v['source_id']));
                $list[$k]['title'] = $info['title'];
                $list[$k]['image_cover'] = $info['image_cover'];
                $list[$k]['publish_time'] = $info['publish_time']>0?$info['publish_time']:$info['update_time'];
                $list[$k]['typeName'] = '资讯';
            } else if ($v['source_type'] == 2) {
                $info = $this->video->get_one(array('id'=>$v['source_id']));
                $list[$k]['title'] = $info['title'];
                $list[$k]['image_cover'] = $info['image_cover'];
                $list[$k]['publish_time'] = $info['update_time'];
                $list[$k]['typeName'] = '视频';
            } else if ($v['source_type'] == 3) {
                $info = $this->picture->get_one(array('id'=>$v['source_id']));
                $list[$k]['title'] = $info['title'];
                $list[$k]['image_cover'] = $info['image_cover'];
                $list[$k]['publish_time'] = $info['update_time'];
                $list[$k]['typeName'] = '图集';
            }
        }
        $pages = $this->db->pages;
        pc_base::load_sys_class('format', '', 0);
        include $this->admin_tpl('lists');
    }
	
	/**
	 * 资源列表
	 */
	function index () {
		$source_type = (int) $_GET['source_type'];
		$id = (int) $_GET['id'];
		if($source_type==1){
            $table="nsrweb_news_nsr";
            $btn_info="资讯";
        }elseif($source_type==2){
            $table="nsrweb_video_nsr";
            $btn_info="视频";
        }elseif($source_type==3){
            $table="nsrweb_picture_nsr";
            $btn_info="图集";
        }
        $goods_model = pc_base::load_model('goods_model'); // 加载model
        $data = $goods_model->get_one(array('id' => $id));
        $show_dialog = $show_validator = true;
        $show_header = '';
        $sql="SELECT n.*,c.id as cid,c.is_top,c.sort  FROM nsrweb_goods_source AS c LEFT JOIN ".$table." AS n ON c.source_id = n.id WHERE n.status = 1";

        // 搜索框
        $title = isset($_GET['title']) ? $_GET['title'] : '';
        $typeid = isset($_GET['typeid']) ? $_GET['typeid'] : '';

        if (isset($_GET['search'])) {
            if ($title) {
                $sql .= " and n.`title` LIKE '%$title%'";
            }
            if ($typeid) {
                $sql .= " and n.type_id = {$typeid}";
            }
        }

        $select_categorys = $this->type->getSource($source_type,$typeid);

        $sql.=" AND c.goods_id=".$id." AND c.source_type = ".$source_type." AND n.siteid = ".$this->siteid." ORDER BY c.is_top DESC,c.sort DESC";

        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $sourceinfo = $this->db->my_listinfo($sql, $page, 10);
        $pages = $this->db->pages;

        include $this->admin_tpl('resources_list');
	}

    /**
     * 添加资源
     */
    public function add ()
    {

        if (isset($_POST['dosubmit'])) {
            $log_content = '在商品id为'.$_POST['goods_id'].'下，';
            $source_type=isset($_REQUEST['contest_source_type'])?$_REQUEST['contest_source_type']:1;
            if($source_type==1){
                $model=$this->news;
                $log_content .= '<span style="color:green;">添加资讯</span>[资讯id：';
                $information =$model->check($_POST['information']);
            }elseif($source_type==2){
                $model=$this->video;
                $log_content .= '<span style="color:green;">添加视频</span>[视频id：';
                $information =$model->check($_POST['manage']);
            }elseif($source_type==3){
                $model=$this->picture;
                $log_content .= '<span style="color:green;">添加图集</span>[图集id：';
                $information =$model->check($_POST['picture']);
            }
            $info = $model->get_one(array('title'=>$information['title'],'status'=>1,'siteid'=>$this->siteid));
            if (!empty($info)) {
                showmessage(L('title-exist'), HTTP_REFERER);
            }
            $id = $model->edit($information);
            if ($id) {
                if ($_POST['contestid']) {
                    $contest_source_model = pc_base::load_model('contest_source_model');
                    $contest_source_model->edit($id, $_POST['contestid'], $source_type);
                }
                $data=array();
                $data['goods_id']=$_POST['goods_id'];
                $data['source_id']=$id;
                $data['source_type']=$source_type;
                $data['created_by'] =  $_SESSION['userid'];
                $data['updated_by'] =  $_SESSION['userid'];

                $data['create_time'] = date("Y-m-d H:i:s",time());
                $data['update_time'] = date("Y-m-d H:i:s",time());
                $res = $this->db->insert($data);

                //记录行为日志
                $log_content .= $id.'，标题：'.$information['title'].']';
                $this->manage_admin_log($log_content);

                if ($res) {
                    showmessage(L('operation_success').L('2s_close'),'blank','','','function set_time() {$("#secondid").html(1);}setTimeout("set_time()", 500);setTimeout("window.close()", 1200);');
                } else {
                    showmessage(L('operation_failure'), HTTP_REFERER);
                }
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }
        } else {
            $show_dialog = $show_validator = true;
            $show_header = '';
            $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;
            $types = $this->type->getSource($source_type);

            if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
                showmessage(L('illegal_action'), HTTP_REFERER);
            }
            $id= (int) $_REQUEST['id'];
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);

            $action_resources="resources";
            $contest_model = pc_base::load_model('contest_model');
            $categorys = $contest_model->now_contest_select();
            if($source_type==1){
                include $this->admin_tpl('information_add','information');
            }elseif($source_type==2){
                include $this->admin_tpl('manage_add','video');
            }elseif($source_type==3){
                include $this->admin_tpl('picture_add','picture');
            }

        }
    }

    /**
     * 选择资源
     */
    public function bindView ()
    {
        $id= $_REQUEST['id'];
        $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;
        $source_array=$this->db->select(array("goods_id"=>$id,"source_type"=>$source_type),"source_id");
        //获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();

        $where=" status=1 and  siteid =" . $this->siteid;

        // 搜索框
        $keywords = isset($_GET['keywords']) ? $_GET['keywords'] : '';
        $typeid = isset($_GET['typeid']) ? $_GET['typeid'] : '';

        if (isset($_GET['search'])) {
            if ($keywords) {
                $where .= " and `title` LIKE '%$keywords%'";
            }
            if ($typeid) {
                $where .= " and type_id = {$typeid}";
            }
        }
        $ids = array();
        if(!empty($source_array)){
            foreach ($source_array as $k => $v) {
                $ids[] = intval($v['source_id']);
            }
            $ids = implode('\',\'', $ids);
            $where.=" and id not in ('$ids')";
        }

        $select_categorys = $this->type->getSource($source_type,$typeid);
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        if($source_type==1){
            $model=$this->news;

        }elseif($source_type==2){
            $model=$this->video;

        }elseif($source_type==3){
            $model=$this->picture;

        }
        $url = "?m=goods&c=resources&a=bindTypeSource&source_type=".$source_type."&goodsid=".$id;
        $infos=$model->listinfo($where,'id DESC',$page,10);
        $pages = $model->pages;
        if($source_type==1){
            include $this->admin_tpl('information_select',"information");
        }elseif($source_type==2){
            include $this->admin_tpl('video_select','video');
        }elseif($source_type==3){
            include $this->admin_tpl('picture_select','picture');
        }

    }

    /**
     * 绑定资源
     */
    public function  bindAction ()
    {
        $id= $_REQUEST['id'];
        $relation=$_REQUEST['relation'];
        $source=explode("|",$relation);
        $data=array();
        $source_type=isset($_REQUEST['source_type'])?$_REQUEST['source_type']:1;


        foreach($source as $k=>$v){

            $data[$k]['goods_id']=$id;
            $data[$k]['source_id']=$v;
            $data[$k]['source_type']=$source_type;
            $data[$k]['created_by'] =  $_SESSION['userid'];
            $data[$k]['updated_by'] =  $_SESSION['userid'];

            $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
            $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
        }
        $res=$this->db->multiInsert($data);

        //记录行为日志
        $source_id = implode(',',$source);
        $source_name = $source_type == 1?'资讯':($source_type == 2?'视频':'图集');
        $log_content = '<span style="color:green;">建立绑定关系</span>[商品id：'.$id.'和'.$source_name.'id：('.$source_id.')的绑定]';
        $this->manage_admin_log($log_content);

        if($res){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"选择成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"选择失败"));
        }
    }

    /**
     * ajax一键导入类型下资源
     */
    public function bindTypeSource ()
    {
        $goodsid= (int) $_REQUEST['goodsid'];
        $source_type=isset($_REQUEST['source_type'])?(int)$_REQUEST['source_type']:1;
        $source_array=$this->db->select(array("goods_id"=>$goodsid,"source_type"=>$source_type),"source_id");
        $type_id = (int) $_REQUEST['type_id'];
        $typeInfo = $this->type->get_one(array('id'=>$type_id));
        //组合条件
        $where = " type_id = ".$type_id;
        if(!empty($source_array)){
            foreach ($source_array as $k => $v) {
                $id[] = intval($v['source_id']);
            }
            $id = implode('\',\'', $id);
            $where.=" and id not in ('$id')";
        }
        if ($typeInfo['parentid'] > 0) {
            if($source_type==1){
                $source_name = '资讯';
                $model=$this->news;
            }elseif($source_type==2){
                $source_name = '视频';
                $model=$this->video;
            }elseif($source_type==3){
                $source_name = '图集';
                $model=$this->picture;
            }
            $info = $model->select($where,'id');
            $data=array();
            $source_id = array();
            foreach($info as $k=>$v){
                $source_id[] = $v['id'];
                $data[$k]['goods_id']=$goodsid;
                $data[$k]['source_id']=$v['id'];
                $data[$k]['source_type']=$source_type;
                $data[$k]['created_by'] =  $_SESSION['userid'];
                $data[$k]['updated_by'] =  $_SESSION['userid'];

                $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
                $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
            }
            if (empty($data)) {
                echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键导入成功"));die;
            }
            $res=$this->db->multiInsert($data);
            if($res){

                //记录行为日志
                $source_id = implode(',',$source_id);
                $log_content = '<span style="color:green;">建立绑定关系</span>[商品id：'.$goodsid.'和'.$source_name.'id：('.$source_id.')的绑定]';
                $this->manage_admin_log($log_content);

                echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"一键导入成功"));
            }else{
                echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"一键导入失败"));
            }
        } else {
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"请选择最底层类型"));
        }
    }

    /**
     * 删除、批量删除
     */
    public function del ()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $source_id = array();
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                    $info = $this->db->get_one(array('id'=>$v));
                    $goods_id = $info['goods_id'];
                    $source_name = $info['source_type'];
                    $source_id[] = $info['source_id'];
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        } else {
            $info = $this->db->get_one(array('id'=>$id));
            $goods_id = $info['goods_id'];
            $source_name = $info['source_type'];
            $source_id[] = $info['source_id'];
        }
        $result = $this->db->delete("id in ('$id')");

        //记录行为日志
        $source_id = implode(',',$source_id);
        $source_name = $source_name == 1?'资讯':($source_name == 2?'视频':'图集');
        $log_content = '<span style="color:red;">解除绑定关系</span>[解除商品id：'.$goods_id.'和'.$source_name.'id：('.$source_id.')的绑定]';
        $this->manage_admin_log($log_content);

        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }
	
    /**
     * 置顶
     */
    public function top ()
    {

        $result = $this->db->update(array('is_top'=> $_GET['is_top']), array(
            'id' => $_GET['id']
        ));
        
        if($result){
            echo  json_encode(array("status"=>true,"code"=>200,"msg"=>"更新成功"));
        }else{
            echo  json_encode(array("status"=>false,"code"=>1000,"msg"=>"更新失败"));
        }
    }

    /**
     * 排序
     */
    public function listorder () 
    {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {

                $result = $this->db->update(array('sort'=>$listorder), array(
                    'id' => $id
                ));

            }
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }
}
?>